package com.sip.stream.base

import android.os.Bundle
import android.view.LayoutInflater
import androidx.viewbinding.ViewBinding
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.observers.DisposableObserver
import me.yokeyword.fragmentation.SupportActivity
import java.lang.reflect.ParameterizedType


abstract class BaseActivity<VB : ViewBinding> : SupportActivity(){

    lateinit var binding: VB

    lateinit var compositeDisposable: CompositeDisposable

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = getViewBindingForActivity(layoutInflater)
        setContentView(binding.root)
        initPage()
    }

    abstract fun initPage()

    @Suppress("UNCHECKED_CAST")
    private fun getViewBindingForActivity(layoutInflater: LayoutInflater): VB {
        val type = javaClass.genericSuperclass as ParameterizedType
        val aClass = type.actualTypeArguments[0] as Class<*>
        val method = aClass.getDeclaredMethod("inflate", LayoutInflater::class.java)
        return method.invoke(null, layoutInflater) as VB
    }


    open fun addDisposable(disposable: Disposable?): Disposable? {
        if (compositeDisposable == null) {
            compositeDisposable = CompositeDisposable()
        }
        compositeDisposable!!.add(disposable!!)
        return disposable
    }

    open fun addDisposableObserver(disposableObserver: DisposableObserver<*>?): DisposableObserver<*>? {
        if (compositeDisposable == null) {
            compositeDisposable = CompositeDisposable()
        }
        compositeDisposable!!.add(disposableObserver!!)
        return disposableObserver
    }

}